package utils

import (
	"alertmanagerWebhook/global"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"net/url"
	"time"
)

func IsPlatformEnabled(platform string) bool {
	switch platform {
	case "wechat":
		return global.Config.QyWeChat.Enabled
	case "dingding":
		return global.Config.DingDing.Enabled
	case "email":
		return global.Config.Email.Enabled
	default:
		return false
	}
}

func GetWebhookURL(platform string) (string, error) {
	switch platform {
	case "wechat":
		return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + global.Config.QyWeChat.QywechatKey, nil
	case "dingding":
		if global.Config.DingDing.SignSecret != "" {
			timestamp, sign, err := generateDingTalkSign(global.Config.DingDing.SignSecret)
			if err != nil {
				global.Logger.Errorf("生成钉钉签名失败: %v", err)
				return "", fmt.Errorf("生成钉钉签名失败: %w", err)
			}
			return fmt.Sprintf("https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%d&sign=%s",
				global.Config.DingDing.DingdingKey,
				timestamp,
				sign), nil
		}
		return "https://oapi.dingtalk.com/robot/send?access_token=" + global.Config.DingDing.DingdingKey, nil
	case "email":
		// 邮件不需要webhook URL，返回空字符串
		return "", nil
	default:
		return "", fmt.Errorf("unsupported platform: %s", platform)
	}
}

// 生成钉钉签名
func generateDingTalkSign(secret string) (timestamp int64, sign string, err error) {
	timestamp = time.Now().UnixNano() / 1e6
	stringToSign := fmt.Sprintf("%d\n%s", timestamp, secret)
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(stringToSign))
	sign = base64.StdEncoding.EncodeToString(h.Sum(nil))
	sign = url.QueryEscape(sign)
	return timestamp, sign, nil
}

